package com.itxialu.reggie.controller;

import com.itxialu.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 *
 * @author shkstart
 * @create 2022-10-28 22:50
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")//从配置文件获取
    private String basePath;

    //上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("上传程序...", file.toString());

        //原始文件名
        String filename = file.getOriginalFilename();
        //文件后缀
        String substring = filename.substring(filename.lastIndexOf("."));

        //UUID重新生成文件名
        String newfilename = UUID.randomUUID().toString() + substring;//toString:返回当前对象的字符串形式

        //创建目录
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //不存在创建
            dir.mkdirs();
        }

        //-------------
        try {
            file.transferTo(new File(basePath + newfilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newfilename);
    }

    //下载(在浏览器端显示图片)
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //输入流，通过输入流读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，将文件写回浏览器，在浏览器展示
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");//固定的。说明是图片格式

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);//把bytes向浏览器写，从0到它的最大长度
                outputStream.flush();//刷新
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
